const errorTypes = require('../constants/error_types')
const service = require('../service/user.service')
const { md5Password } = require('../utils/password_handle')

// 创建用户之前对数据进行校验
const verifyUser = async (ctx, next) => {
  console.log('验证用户账号密码是合法化middleware')
  const { name, password } = ctx.request.body
  //   1.判断用户名和密码不能为空
  if (!name || !password) {
    const error = new Error(errorTypes.NAME_OR_PASSWORD_IS_REQUIRED)
    return ctx.app.emit('error', error, ctx)
  }
  //   2.判断当前用户是否已经被注册过
  const results = await service.getUserByname(name)
  if (results.length) {
    const error = new Error(errorTypes.USER_ALREADY_EXISTS)
    return ctx.app.emit('error', error, ctx)
  }
  await next()
}
// 对明文密码进行处理
const handlePassword = async (ctx, next) => {
  console.log('用户密码MD5加密middleware')
  const { password } = ctx.request.body
  ctx.request.body.password = md5Password(password)
  await next()
}
module.exports = {
  verifyUser,
  handlePassword,
}
